<template>
  <div class="num-wrapper">
    <div class="sub" @click="decrement">-</div>
    <div class="num">{{ item.quantity }}</div>
    <div class="add" @click="increment">+</div>
  </div>
</template>

<script>
import api from '@/api'
export default {
  name: 'CartNum',
  props: {
    item: {
      type: Object,
      default() {
        return { quantity: 1 }
      }
    }
  },
  methods: {
    decrement() {
      if (this.item.quantity > 1) {
        this.item.quantity--
        this.item.selected = true
        // api delay
        api.Cart.decrement({ ...this.item }).then()
      }
    },
    increment() {
      if (this.item.quantity < +this.item.product.stock) {
        this.item.quantity++
        this.item.selected = true
        // 延迟处理数据库
        api.Cart.increment({ ...this.item }).then()
      } else {
        this.$createToast({
          type: 'error',
          txt: '库存不足',
          time: 1000
        }).show()
      }
    }
  }
}
</script>

<style scoped lang="stylus">
$size = 22px
$button = $size + 5px

.num-wrapper
  display flex
  text-align center
  .sub, .num, .add
    border 1px solid #dcdcdc
    min-width $size
    height $size
    line-height $size
  .sub, .add
    min-width $button
    font-weight 700
  .sub
    border-right none
    border-top-left-radius 10px
    border-bottom-left-radius 10px
  .add
    border-left none
    border-top-right-radius 10px
    border-bottom-right-radius 10px
</style>
